import jwt
import datetime
from django.conf import settings

def generate_verify_email_url(user):
    """
    生成邮箱验证链接（使用 PyJWT）
    :param user: 当前登录用户
    :return: verify_url
    """
    # 设置过期时间（当前 UTC 时间 + 1小时）
    now_utc = datetime.datetime.now(datetime.timezone.utc)
    expiration = now_utc + datetime.timedelta(hours=1)

    # 构造 payload 数据
    payload = {
        'user_id': user.id,
        'email': user.email,
        'exp': expiration,  # 过期时间
        'iat': now_utc  # 签发时间，使用 UTC 时间
    }

    # 生成 token
    token = jwt.encode(payload, key=settings.SECRET_KEY, algorithm='HS256')

    return token

def check_verify_email_token(token):
  """
  验证token
  :param token: token
  :return: user
  """
  # 1. 解密token
  from jwt import PyJWTError
  try:
    payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms='HS256')
  except Exception as e:
    print("错误：", str(e))
    return None
  # 2. 获取user_id
  user_id = payload.get('user_id')
  # 3. 获取email
  email = payload.get('email')
  # 4. 查询user
  from apps.users.models import User
  try:
    user = User.objects.get(id=user_id, email=email)
  except User.DoesNotExist:
    return None
  # 5. 返回user
  return user
